import { defineStore } from "pinia";
import {
  fetchScheSettings,
  createScheSetting,
  updateScheSetting,
  deleteScheSetting,
  fetchAllScheSettings,
} from "@/api/schedule/setting";
import type { IScheSetting } from "@/api/schedule/setting";
import { ref, computed } from "vue";
import { useUserStore } from "@/stores/modules/user";

export const useScheSettingStore = defineStore("scheSetting", () => {
  const scheSettings = ref<IScheSetting[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  const pagination = ref({
    current: 1,
    size: 100,
    total: 0,
  });

  const searchQuery = ref("");

  // 获取排班设置列表(分页功能)
  const getScheSettings = async () => {
    try {
      loading.value = true;
      error.value = null;
      const params = {
        settingName: searchQuery.value,
        deptId: useUserStore().userInfo.staff.deptId, // 待修改，从pinia拿
        status: 1, // 只获取正常状态的排班设置
        page: pagination.value.current - 1,
        size: pagination.value.size,
      };

      const res = await fetchScheSettings(params);
      scheSettings.value = res.data.content;
      pagination.value.total = res.data.totalElements;
    } catch (err) {
      error.value = "获取排班设置列表失败";
      console.error("获取排班设置列表失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 新增排班设置
  const addScheSetting = async (data: IScheSetting) => {
    try {
      loading.value = true;
      await createScheSetting(data);
      await getScheSettings();
    } catch (err) {
      console.error("新增排班设置失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新排班设置
  const editScheSetting = async (data: IScheSetting) => {
    try {
      loading.value = true;
      await updateScheSetting(data);
      await getScheSettings();
    } catch (err) {
      console.error("更新排班设置失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 删除排班设置
  const removeScheSetting = async (id: number | string) => {
    try {
      loading.value = true;
      await deleteScheSetting(id);
      await getScheSettings();
    } catch (err) {
      console.error("删除排班设置失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 获取所有排班设置
  const allScheSettings = async () => {
    try {
      loading.value = true;
      error.value = null;
      const res = await fetchAllScheSettings(useUserStore().userInfo.staff.deptId);
      scheSettings.value = res.data;
    } catch (err) {
      error.value = "获取排班设置列表失败";
      console.error("获取排班设置列表失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  return {
    scheSettings,
    loading,
    error,
    pagination,
    searchQuery,
    getScheSettings,
    addScheSetting,
    editScheSetting,
    removeScheSetting,
    allScheSettings,
  };
});